<template>
  <div>
    <a-space class="operator">
      <a-button @click="addNew" type="primary">新建</a-button>
      <!-- <a-button >批量操作</a-button>
      <a-dropdown>
        <a-menu @click="handleMenuClick" slot="overlay">
          <a-menu-item key="delete">删除</a-menu-item>
          <a-menu-item key="audit">审批</a-menu-item>
        </a-menu>
        <a-button>
          更多操作 <a-icon type="down" />
        </a-button>
      </a-dropdown> -->
    </a-space>
    <div class="card-list">
      <a-list
        :grid="{ gutter: 24, lg: 6, md: 2, sm: 1, xs: 1 }"
        :dataSource="dataSource"
      >
        <a-list-item slot="renderItem" slot-scope="item">
          <template v-if="item.add">
            <a-button class="new-btn" type="dashed">
              <a-icon type="plus" />新增产品
            </a-button>
          </template>
          <template v-else>
            <a-card hoverable style="width: 240px">
              <img slot="cover" alt="example" :src="avatar + item.fileHash" />
              <a-card-meta :title="item.goodsName">
                <template slot="description">
                  <!-- <p class="ps" v-html="item.goodsDescription"></p> -->
                  <br />
                  价格：￥{{ item.goodsPrice }}
                  <br />
                  添加时间：{{ item.createTime | capitalize }}
                </template>
              </a-card-meta>
              <p class="shelve" @click="editor(item.id)">编辑商品</p>
              <p class="shelves" @click="deletes(item.id)">下架商品</p>
            </a-card>
            <!-- <a-card :hoverable="true">
              <a-card-meta >
                <div style="margin-bottom: 3px" slot="title">{{item.goodsName}}</div>
                <a-avatar class="card-avatar" slot="avatar" :src="avatar" size="large" />
                <div class="meta-content" slot="description">{{item.goodsDescription}}</div>
              </a-card-meta>
              <a slot="actions">价格：￥{{item.goodsPrice}}</a>
              <a slot="actions">添加时间：{{item.createTime | capitalize}}</a>
            </a-card> -->
          </template>
        </a-list-item>
      </a-list>
    </div>
    <!--  -->
    <a-modal
      v-model="visible"
      title="添加商品"
      @cancel="resetForm"
      :footer="null"
      class="mmmm"
      width="1220px"
    >
      <a-form-model
        ref="ruleForm"
        :model="form"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 14 }"
      >
        <a-form-model-item label="商品名称" prop="goodsname">
          <a-input v-model="form.goodsname" />
        </a-form-model-item>

        <a-form-model-item label="商品背景" prop="productionBackground">
          <a-input v-model="form.productionBackground" />
        </a-form-model-item>

        <a-form-model-item label="作者介绍" prop="authorAbout">
          <a-input v-model="form.authorAbout" />
        </a-form-model-item>

        <a-form-model-item label="发行方" prop="issuer">
          <a-input v-model="form.issuer" />
        </a-form-model-item>

        <a-form-model-item label="商品价格" prop="price">
          <a-input-number v-model="form.price" :min="1" />
        </a-form-model-item>
        <a-form-model-item label="商品描述" prop="description">
          <!-- <a-input v-model="form.description" type="textarea" /> -->

          <!-- 使用 v-model 进行双向的数据绑定 -->
          <quill-editor v-model="form.description"></quill-editor>
        </a-form-model-item>
        <a-form-model-item label="商品图片" :help="extra" required>
          <a-upload
            ref="upload"
            name="avatar"
            list-type="picture-card"
            :file-list="fileList"
            action="2"
            :before-upload="beforeUpload"
            :customRequest="customRequest"
            @change="handleChange"
          >
            <img class="imgs" v-if="imageUrl" :src="imageUrl" alt="avatar" />
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">商品图片</div>
            </div>
          </a-upload>
        </a-form-model-item>
        <a-form-model-item :wrapper-col="{ span: 14, offset: 6 }">
          <a-button type="primary" @click="onSubmit"> 提交 </a-button>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!--  -->
  </div>
</template>

<script>
import { message } from 'ant-design-vue'
import {
  getGoodsAll,
  addGoods,
  addFileData,
  details,
  editors,
} from '@/services/goods'
import { oddGoodss } from '@/services/goods'
import axios from 'axios'
export default {
  name: 'CardList',
  data() {
    return {
      id: null,
      isall: true,
      visible: false,
      linkList: [
        { icon: 'rocket', href: '/#/', title: '快速开始' },
        { icon: 'info-circle-o', href: '/#/', title: '产品简介' },
        { icon: 'file-text', href: '/#/', title: '产品文档' },
      ],
      extraImage: '',
      dataSource: [],
      avatar: 'http://82.157.149.151:8080/ipfs/',

      form: {
        goodsname: '',
        price: undefined,
        description: '',
        productionBackground: '',
        authorAbout: '',
        issuer: '',
      },

      rules: {
        goodsname: [
          { required: true, message: '请输入商品名称！', trigger: 'blur' },
        ],
        price: [
          { required: true, message: '请输入商品价格！', trigger: 'blur' },
        ],
        description: [
          { required: true, message: '请输入商品描述！', trigger: 'blur' },
        ],
        productionBackground: [
          { required: true, message: '请输入商品背景！', trigger: 'blur' },
        ],
        authorAbout: [
          { required: true, message: '请输入作者背景！', trigger: 'blur' },
        ],
        issuer: [
          { required: true, message: '请输入发行方！', trigger: 'blur' },
        ],
      },

      imageUrl: '',
      fileList: [],
      loading: false,
      fileId: null,
      extra: '',
    }
  },
  methods: {
    // 删除
    async deletes(id) {
      console.log(id)
      console.log(oddGoodss)
      oddGoodss(id).then((res) => {
        console.log(res.data)
        if (res.data.code === 0) {
          message.success('下架成功')
        } else {
          message.error('下架失败')
        }
        this.initList()
      })
    },
    // 编辑
    async editor(id) {
      this.id = id
      this.visible = true
      this.isall = true
      if (this.isall) {
        const { data: res } = await details({ goodsId: id })
        console.log(res.data)

        this.form.goodsname = res.data.goodsName
        this.form.price = res.data.goodsPrice
        this.form.description = res.data.goodsDescription
        this.imageUrl = this.avatar + res.data.fileHash
        this.fileId = res.data.fileHash
        this.form.productionBackground = res.data.productionBackground
        this.form.authorAbout = res.data.authorAbout
        this.form.issuer = res.data.issuer
      }
    },
    // 编辑提交
    async editorss() {
      const res = await editors({
        id: this.id,
        goodsName: this.form.goodsname,
        goodsPrice: this.form.price,
        goodsDescription: this.form.description,
        fileHash: this.fileId,
        productionBackground: this.form.productionBackground,
        authorAbout: this.form.authorAbout,
        issuer: this.form.issuer,
      })
      console.log(res)
    },

    //新建
    addNew() {
      this.isall = false
      this.visible = true
      this.form.goodsname = ''
      this.form.price = undefined
      this.form.description = ''
      this.imageUrl = ''
      this.fileId = null
      this.imageUrl = ''
    },
    resetForm() {
      this.$refs.ruleForm.resetFields()
      this.visible = false
      this.fileList = []
      this.fileId = null
      this.extra = ''
    },
    // 提交
    onSubmit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          if (this.fileId) {
            if (this.isall) {
              // 编辑
              const res = await this.editorss()
              console.log(res)
              this.$message.success(`修改成功`)
              this.initList()
              this.visible = false
              console.log(this.isall)
            } else {
              // 新建
              const res = await this.addgoods()
              console.log(res)
              this.visible = false
            }
          } else {
            this.extra = '请选择商品图片'
          }
        } else {
          return false
        }
      })

      this.initList()
    },

    // 添加
    addgoods() {
      addGoods({
        goodsName: this.form.goodsname,
        goodsPrice: this.form.price,
        goodsDescription: this.form.description,
        fileHash: this.fileId,
        productionBackground: this.form.productionBackground,
        authorAbout: this.form.authorAbout,
        issuer: this.form.issuer,
      }).then((res) => {
        console.log(res)
        const loginRes = res.data
        if (loginRes.code == 0) {
          this.$message.success(`添加成功！`)
          this.initList()
          this.resetForm()
        }
      })
      this.isall = false
    },

    initList() {
      getGoodsAll().then((res) => {
        console.log(res)
        const loginRes = res.data
        if (loginRes.code == 0) {
          this.dataSource = loginRes.data
        }
      })
    },
    handleChange({ fileList }) {
      this.fileList = fileList
    },
    beforeUpload(file, fileList) {
      // this.fileList = [fileList]
      // this.fileList = [file];
      // this.fileList = [...this.fileList, file]
      console.log(file, fileList)
      return true
    },
    // http://82.157.149.151:5001/api/v0/add?stream-channels=true&pin=false&wrap-with-directory=false&progress=false
    customRequest(file) {
      console.log('---------customRequest', file)

      // const { fileList } = this
      // console.log(fileList)
      const formData = new FormData()
      // fileList.forEach((file) => {
      formData.append('files[]', file)
      // })
      console.log(formData)
      axios({
        url: '/api/v0/add',
        method: 'POST',
        data: formData,
        params: {
          'stream-channels': true,
          pin: false,
          'wrap-with-directory': false,
          progress: false,
        },
      }).then((res) => {
        console.log(res)
        file.onSuccess(res.data, file)
        if (res.status == 200) {
          addFileData({
            fileName: res.data.Name,
            fileHash: res.data.Hash,
            userId: 1,
          }).then((fileres) => {
            console.log(fileres)
            this.fileId = fileres.data.data
          })
        }
      })
    },
  },
  mounted() {
    this.initList()

    axios({
      url: '/api/v0/ls',
      method: 'post',
      params: {
        arg: '',
      },
    }).then((res) => {
      console.log(res)
    })
  },
  filters: {
    capitalize: function (value) {
      if (!value) return ''
      var date = new Date(value)
      var year = date.getFullYear()
      var month =
        date.getMonth() + 1 > 9
          ? date.getMonth() + 1
          : '0' + (date.getMonth() + 1)
      var day = date.getDate() > 9 ? date.getDate() : '0' + date.getDate()
      var h = date.getHours() > 9 ? date.getHours() : '0' + date.getHours()
      var m =
        date.getMinutes() > 9 ? date.getMinutes() : '0' + date.getMinutes()
      return year + '-' + month + '-' + day + ' ' + h + ':' + m
    },
  },
}
</script>

<style lang="less" scoped>
.ps {
  // background-color: pink;
  margin-bottom: -30px;
}
.ant-modal-content {
  width: 1920px;
  height: 100%;
}
// 设置富文本编辑器的默认最小高度
/deep/ .ql-editor {
  min-height: 300px;
}
.card-avatar {
  width: 48px;
  height: 48px;
  border-radius: 48px;
}
.new-btn {
  border-radius: 2px;
  width: 100%;
  height: 187px;
}

.imgs {
  width: 200px;
  height: 200px;
}
.meta-content {
  position: relative;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  height: 64px;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}
.operator {
  margin-bottom: 18px;
}
::v-deep {
  .ant-form-explain {
    color: #f5222f;
  }
  .ant-card-cover {
    img {
      width: 238px;
      height: 238px;
    }
  }
}
.shelves {
  float: right;
  // display: inline-block;
  width: 60px;
  height: 20px;
  // background-color: red;
  color: red;
}
.shelve {
  float: left;
  // display: inline-block;
  width: 60px;
  height: 20px;
  // background-color: red;
  color: blue;
}
</style>
